<?php
require_once 'includes/header.php';
require_once 'includes/functions.php';

$db = Database::getInstance();

// 检查是否有管理员权限
if (!$auth->isLoggedIn() || $auth->getUserData()['role'] !== 'admin') {
    $_SESSION['flash_message'] = '您没有执行此操作的权限';
    $_SESSION['flash_type'] = 'danger';
    header('Location: index.php');
    exit;
}

$action = isset($_GET['action']) ? $_GET['action'] : '';
$success = false;
$message = '';

switch ($action) {
    // 清除缓存
    case 'clear_cache':
        $cacheDir = __DIR__ . '/../cache/';
        $message = clearCache($cacheDir);
        $success = true;
        break;
        
    // 优化数据库
    case 'optimize_db':
        $result = optimizeDatabase($db);
        $message = $result['message'];
        $success = $result['success'];
        break;
        
    // 生成网站地图
    case 'generate_sitemap':
        $result = generateSitemap($db);
        $message = $result['message'];
        $success = $result['success'];
        break;
        
    // 备份数据库
    case 'backup_db':
        $result = backupDatabase($db);
        $message = $result['message'];
        $success = $result['success'];
        break;
        
    // 默认情况
    default:
        header('Location: settings.php');
        exit;
}

// 设置提示消息
if ($success) {
    $_SESSION['flash_message'] = $message;
    $_SESSION['flash_type'] = 'success';
} else {
    $_SESSION['flash_message'] = '操作失败：' . $message;
    $_SESSION['flash_type'] = 'danger';
}

// 重定向回设置页面
header('Location: settings.php');
exit;

/**
 * 清除缓存目录
 * 
 * @param string $cacheDir 缓存目录路径
 * @return string 结果消息
 */
function clearCache($cacheDir) {
    if (!is_dir($cacheDir)) {
        return '缓存目录不存在';
    }
    
    $count = 0;
    $files = glob($cacheDir . '*');
    
    foreach ($files as $file) {
        if (is_file($file)) {
            @unlink($file);
            $count++;
        }
    }
    
    return "已成功清除 {$count} 个缓存文件";
}

/**
 * 优化数据库
 * 
 * @param Database $db 数据库实例
 * @return array 包含成功状态和消息的数组
 */
function optimizeDatabase($db) {
    try {
        // 获取所有表名
        $tables = $db->fetchColumn(
            "SHOW TABLES",
            [],
            true
        );
        
        if (empty($tables)) {
            return [
                'success' => false,
                'message' => '未找到数据表'
            ];
        }
        
        // 优化每个表
        $optimizedCount = 0;
        foreach ($tables as $table) {
            $db->execute("OPTIMIZE TABLE `{$table}`");
            $optimizedCount++;
        }
        
        return [
            'success' => true,
            'message' => "已成功优化 {$optimizedCount} 个数据表"
        ];
    } catch (Exception $e) {
        return [
            'success' => false,
            'message' => $e->getMessage()
        ];
    }
}

/**
 * 生成网站地图
 * 
 * @param Database $db 数据库实例
 * @return array 包含成功状态和消息的数组
 */
function generateSitemap($db) {
    try {
        $sitemapFile = __DIR__ . '/../sitemap.xml';
        $baseUrl = isset($_SERVER['HTTP_HOST']) ? ('http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . $_SERVER['HTTP_HOST']) : '';
        
        // 创建XML文档
        $xml = new DOMDocument('1.0', 'UTF-8');
        $xml->formatOutput = true;
        
        // 创建urlset元素
        $urlset = $xml->createElement('urlset');
        $urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
        $xml->appendChild($urlset);
        
        // 添加首页
        $url = $xml->createElement('url');
        $loc = $xml->createElement('loc', $baseUrl . '/');
        $url->appendChild($loc);
        $urlset->appendChild($url);
        
        // 添加游戏页面
        $games = $db->fetchAll("SELECT id, updated_at FROM " . DB_PREFIX . "games WHERE status = 'active'");
        foreach ($games as $game) {
            $url = $xml->createElement('url');
            $loc = $xml->createElement('loc', $baseUrl . '/game.php?id=' . $game['id']);
            $url->appendChild($loc);
            
            if (!empty($game['updated_at'])) {
                $lastmod = $xml->createElement('lastmod', date('Y-m-d', strtotime($game['updated_at'])));
                $url->appendChild($lastmod);
            }
            
            $urlset->appendChild($url);
        }
        
        // 保存文件
        $xml->save($sitemapFile);
        
        return [
            'success' => true,
            'message' => '网站地图已成功生成：' . $sitemapFile
        ];
    } catch (Exception $e) {
        return [
            'success' => false,
            'message' => $e->getMessage()
        ];
    }
}

/**
 * 备份数据库
 * 
 * @param Database $db 数据库实例
 * @return array 包含成功状态和消息的数组
 */
function backupDatabase($db) {
    try {
        $backupDir = __DIR__ . '/../backups/';
        
        // 如果备份目录不存在，则创建
        if (!is_dir($backupDir)) {
            if (!mkdir($backupDir, 0755, true)) {
                return [
                    'success' => false,
                    'message' => '无法创建备份目录'
                ];
            }
        }
        
        // 创建.htaccess文件以保护备份目录
        $htaccessFile = $backupDir . '.htaccess';
        if (!file_exists($htaccessFile)) {
            file_put_contents($htaccessFile, "Deny from all\n");
        }
        
        // 获取数据库信息
        $dbInfo = $db->getConnectionInfo();
        
        // 生成备份文件名
        $backupFile = $backupDir . 'backup_' . date('Y-m-d_H-i-s') . '.sql';
        
        // 根据操作系统执行备份命令
        if (stripos(PHP_OS, 'WIN') === 0) {
            // Windows系统
            $command = "\"C:\\Program Files\\MySQL\\MySQL Server 5.7\\bin\\mysqldump\" --host={$dbInfo['host']} --user={$dbInfo['username']} --password={$dbInfo['password']} {$dbInfo['database']} > \"$backupFile\"";
        } else {
            // Linux/Unix系统
            $command = "mysqldump --host={$dbInfo['host']} --user={$dbInfo['username']} --password={$dbInfo['password']} {$dbInfo['database']} > \"$backupFile\"";
        }
        
        // 执行命令
        exec($command, $output, $returnVar);
        
        if ($returnVar !== 0) {
            return [
                'success' => false,
                'message' => '备份命令执行失败，错误代码: ' . $returnVar
            ];
        }
        
        // 压缩备份文件
        $zipFile = $backupFile . '.zip';
        $zip = new ZipArchive();
        if ($zip->open($zipFile, ZipArchive::CREATE) === true) {
            $zip->addFile($backupFile, basename($backupFile));
            $zip->close();
            
            // 删除原始SQL文件，只保留ZIP文件
            @unlink($backupFile);
            
            return [
                'success' => true,
                'message' => '数据库备份已成功创建：' . $zipFile
            ];
        } else {
            return [
                'success' => false,
                'message' => '无法创建ZIP文件'
            ];
        }
    } catch (Exception $e) {
        return [
            'success' => false,
            'message' => $e->getMessage()
        ];
    }
}
?> 